(function ($) {
    $.fn.ui_table = function (url, opts, setting) {
        $.fn.ui_table.url = url;
        $.fn.ui_table.opts = $.extend({}, {
            searchcol: '',
            searchtext: '',
            sortcol: '',
            sorttext: '',
            pagesize: 10,
            pageNum: 1
        }, opts);

        $.fn.ui_table.setting = setting;

        return this.each(function () {
            inittable($(this));
        });
    };
    $.fn.ui_table.url = "";
    $.fn.ui_table.opts = {};
    $.fn.ui_table.setting = {};
    $.fn.ui_table.rerush = rerush;
    $.fn.ui_table.selectids = [];

    function inittable($this) {
        $this.html(creategrid());
        rerush($this);
        initevent($this);
    }

    function creategrid() {
        var table = '<div class="ui-table"><div class="ui-table-header"><div class="ui-table-pagesize"><div class="ui-dropdown"><div>显示' + $.fn.ui_table.setting.pagesize[0] + '条</div><ul>';
        for (var i = 0; i < $.fn.ui_table.setting.pagesize.length; i++) {
            table += '<li data-val="' + $.fn.ui_table.setting.pagesize[i] + '">显示' + $.fn.ui_table.setting.pagesize[i] + '条</li>';
        }
        table += '</ul><input type="hidden" value=' + $.fn.ui_table.setting.pagesize[0] + '/><i></i></div></div>';
        table += '<div class="ui-table-option"></div>';
        table += '<div class="ui-dropdown-search"><div class="ui-dropdown"><div>' + $.fn.ui_table.setting.searchtext[0] + '</div><ul>';
        for (var i = 0; i < $.fn.ui_table.setting.searchcol.length; i++) {
            table += '<li data-val="' + $.fn.ui_table.setting.searchcol[i] + '">' + $.fn.ui_table.setting.searchtext[i] + '</li>';
        }
        table += '</ul><input type="hidden" value=' + $.fn.ui_table.setting.searchcol[0] + '/><i></i></div><div class="ui-search"><input type="text" placeholder="请输入搜索内容" value="" /><a></a></div></div></div><div class="ui-table-body"><table><thead><tr>';
        table += $.fn.ui_table.setting.header;
        table += '</tr></thead><tbody>';
        //table += creatrow();
        table += '</tbody></table></div><div class="ui-table-footer">';
        //table += CreatPage();
        table += '</div></div>';
        return table;
    }
    /// {
    ///      'data': [{'ID':'1', 'Name':'aaa','Age':'1'],{'ID':'1', 'Name':'aaa','Age':'1'],{'ID':'1', 'Name':'aaa','Age':'1']],
    ///      'total':1000,
    /// }
    function rerush($this) {
        $this.find("tbody").html("");
        $this.find(".ui-table-footer").html('<div class="ui-table-loading"></div>');
        $.post($.fn.ui_table.url, $.fn.ui_table.opts,
            function (data) {
                //data = eval('(' + data + ')');
                //data = data.rows;
                  data ={'total':data.total,'data':data.rows};
                  //data = JSON.parse(data);
                console.log(data);
                if (data !== "" && data.data.length > 0) {
                    $this.find("tbody").html(creatrow(data));
                    $this.find(".ui-table-option").html(creatoption(data));
                    $this.find(".ui-table-footer").html(creattip($.fn.ui_table.opts.pagecurrent, $.fn.ui_table.opts.pagesize, data.total));
                } else {
                    //$this.find("tbody").html("");
                    $this.find(".ui-table-footer").html('<div class="ui-table-nodata">没有记录</div>');
                }
            });
    }

    function creatrow(data) {
        var table = "";
        for (var i = 0; i < data.data.length; i++) {
            var row = $.fn.ui_table.setting.body;
            for (var j in data.data[i]) {
                row = row.replaceAll("#" + j, data.data[i][j]);
            }
            table += "<tr>" + row + "</tr>";
        }
        for (var j in data.data[0]) {
            $.fn.ui_table.setting.option = $.fn.ui_table.setting.option.replaceAll("#" + j, data.data[0][j]);
        }
        return table;
    }

    function creatoption(data) {
        for (var j in data.data[0]) {
            $.fn.ui_table.setting.option = $.fn.ui_table.setting.option.replaceAll("#" + j, data.data[0][j]);
        }
        return $.fn.ui_table.setting.option;
    }

    function creattip(pagecurrent, pagesize, Total) {
        pagecurrent = parseInt(pagecurrent);
        pagesize = parseInt(pagesize);
        Total = parseInt(Total);

        var totalpage = Math.ceil(Total / pagesize);

        if (pagecurrent < 1)
            pagecurrent = 1;
        if (pagecurrent > totalpage)
            pagecurrent = totalpage;

        var page = '<div class="ui-table-tip"><span>共' + Total + '条记录</span><div class="ui-table-pagelist"><a d="1">首页</a>';
        if (pagecurrent > 1) {
            page += '<a d="' + (pagecurrent - 1) + '">上一页</a>';
        }

        var mon = 5 - pagecurrent > 0 ? 5 - pagecurrent : 0;
        for (var i = pagecurrent - 4; i <= +pagecurrent + 5 + mon; i++) {
            if (i >= 1 && i < pagecurrent) {
                page += '<a d=' + i + '>' + i + '</a>';
            }
            if (i == pagecurrent) {
                page += '<span>' + pagecurrent + '</span>';
            }
            if (i > pagecurrent && i <= totalpage) {
                page += '<a d=' + i + '>' + i + '</a>';
            }
        }
        if (pagecurrent < totalpage) {
            page += '<a d="' + (pagecurrent + 1) + '">下一页</a>';
        }
        page += '<a d="' + totalpage + '">末页</a></div></div>';
        return page;
    }

    function initevent($this) {

        $this.find("thead .ui-checkbox").click(function () {
            if ($(this).hasClass("checked")) {
                $this.find("tbody .ui-checkbox").removeClass("checked");
            } else {
                $this.find("tbody .ui-checkbox").addClass("checked");
            }
        });

        $(document).on("click", ".ui-checkbox", function () {
            $.fn.ui_table.selectids = [];
            $this.find("tbody .ui-checkbox.checked").each(function () {
                $.fn.ui_table.selectids.push($(this).attr('data'));
            });
            var option = $.fn.ui_table.setting.option.replaceAll("###", $.fn.ui_table.selectids.join('_'));
            $this.find(".ui-table-option").html(option);
        });

        $this.find(".ui-table-pagesize li").click(function () {
            $.fn.ui_table.opts.pagesize = $(this).attr("data-val");
            $.fn.ui_table.opts.pagecurrent = 1;
            rerush($this);
        });

        $this.find(".ui-dropdown-search li").click(function () {
            $.fn.ui_table.opts.searchcol = $(this).attr("data-val");
        });

        $this.find(".ui-dropdown-search a").click(function () {
            $.fn.ui_table.opts.searchtext = $(this).prev().val();
            $.fn.ui_table.opts.pagecurrent = 1;
            rerush($this);
        });

        $this.delegate(".ui-table-footer a", "click", function () {
            $.fn.ui_table.opts.pagecurrent = $(this).attr("d");
            rerush($this);
        });

        $this.find(".ui-table-sort").click(function () {
            if ($.fn.ui_table.opts.sortcol == $(this).attr('d')) {
                if ($.fn.ui_table.opts.sorttext == 'asc') {
                    $.fn.ui_table.opts.sorttext = 'desc';
                } else {
                    $.fn.ui_table.opts.sorttext = 'asc';
                }
            } else {
                $.fn.ui_table.opts.sortcol = $(this).attr('d');
                $.fn.ui_table.opts.sorttext = 'asc';
            }
            $.fn.ui_table.opts.sortcol = $(this).attr('d');

            rerush($this);
        });
    }
})(jQuery);